import { View, Text } from "@tarojs/components";
import Taro, { getCurrentInstance } from "@tarojs/taro";
import React, { useState, useEffect, useRef } from "react";
import "./index.scss";
import closeIcon from "../../assets/close-white.png";
import defaultImg from "../../assets/default.png";
import classNames from "classnames";
import { AllChannel } from "../../components/all-channel";
import { InviteMember } from "../../components/invite-member";
import { Logout } from "../../components/logout";
import {
  ImageWithTextType,
  StackAvatars,
} from "../../components/stack-avatars";
import {
  fetchMember,
  fetchPartner,
  fetchUserInfo,
  fetchChannel,
} from "../../api";
import {
  IChannel,
  ICurChannelInfo,
  IMember,
  IPartner,
  IUserInfo,
} from "src/interfaces";
import { getOssUrl, setStore, scrollToCenter } from "../../utils";
import { ImageWithText, Image } from "../img";

interface Props {
  curChannelInfo: ICurChannelInfo;
  setCurChannelInfo: Function;
}
export const Header = ({ curChannelInfo, setCurChannelInfo }: Props) => {
  const [spaceId, setSpaceId] = useState<string>("");
  const [channelList, setChannelList] = useState<IChannel[]>([]);
  const [memberList, setMemberList] = useState<(string | ImageWithTextType)[]>(
    []
  );
  const [partnerInfo, setPartnerInfo] = useState<IPartner>();
  const [userInfo, setUserInfo] = useState<IUserInfo>();
  const [isOpened, setIsOpened] = useState(false);
  const [isOpenedLogout, setIsOpenedLogout] = useState(false);
  const [isOpenedInvite, setIsOpenedInvite] = useState(false);
  useEffect(() => {
    const { router } = getCurrentInstance();
    const spaceId = router?.params?.spaceId || "";
    if (!spaceId) {
      alert("没有空间id");
      return;
    }
    setSpaceId(spaceId);
    const init = async () => {
      const [getMemberRes, getPartnerRes, getUserInfoRes, getChannelRes] =
        await Promise.all([
          fetchMember(spaceId),
          fetchPartner(spaceId),
          fetchUserInfo(),
          fetchChannel(spaceId),
        ]);
      // 频道信息
      if (getChannelRes?.code === 0) {
        setChannelList([
          {
            id: "index",
            type: "index",
            name: "首页",
          },
          ...getChannelRes?.data,
        ]);
      } else {
        alert(getChannelRes?.message);
      }
      // 用户信息
      if (getUserInfoRes?.code === 0) {
        setUserInfo(getUserInfoRes?.data);
        setStore("userInfo", JSON.stringify(getUserInfoRes?.data));
      } else {
        alert(getUserInfoRes?.message);
      }
      // 成员信息
      if (getMemberRes?.code === 0) {
        const memberListIcons = getMemberRes?.data
          .filter((item: IMember) => item?.memberType === "out")
          .map((item: IMember) => {
            return {
              src: getOssUrl({
                bucketName: item?.img?.bucketName,
                path: item?.img?.path,
              }),
              text: item?.nickName,
            };
          });
        setMemberList(memberListIcons);
      } else {
        alert(getMemberRes?.message);
      }
      // 合作方信息
      if (getPartnerRes?.code === 0) {
        setPartnerInfo(getPartnerRes?.data);
      } else {
        alert(getPartnerRes?.message);
      }
    };
    init();
  }, []);
  const menuEleRef = useRef<HTMLDivElement>(null);
  // const scrollToCenter = () => {
  //   const menuDom = document?.querySelector(".tabs-menu") as HTMLElement;
  //   const curTabDom = document?.querySelector(
  //     ".tabs-menu .active"
  //   ) as HTMLElement;

  //   const menuWidth = menuDom?.clientWidth;
  //   const curTabOffsetLeft = curTabDom.offsetLeft;
  //   const boxWidth = document?.querySelector(".tabs")?.clientWidth as number;
  //   if (curTabOffsetLeft < boxWidth / 2) {
  //     menuDom?.scrollTo(0, 0);
  //   } else {
  //     console.log(curTabDom?.offsetWidth);
  //     menuDom?.scrollTo(
  //       curTabOffsetLeft - boxWidth / 2 + curTabDom?.offsetWidth / 2,
  //       0
  //     );
  //   }
  // };
  return (
    <div className="header">
      <div className="padding-16">
        <div className="display-flex icon-container">
          <div className="company-icons">
            <Image
              className="party-a icon vertical-align-m"
              src={
                partnerInfo?.partnerLogo?.bucketName
                  ? getOssUrl({
                      bucketName: partnerInfo?.partnerLogo?.bucketName || "",
                      path: partnerInfo?.partnerLogo?.path || "",
                    })
                  : defaultImg
              }
            />
            <Image
              className="icon-connection vertical-align-m"
              src={closeIcon}
            />
            <Image
              className="party-b icon vertical-align-m"
              src={
                partnerInfo?.teamLogo?.bucketName
                  ? getOssUrl({
                      bucketName: partnerInfo?.teamLogo?.bucketName || "",
                      path: partnerInfo?.teamLogo?.path || "",
                    })
                  : defaultImg
              }
            />
          </div>
          {userInfo && (
            <ImageWithText
              className="user-icon"
              src={getOssUrl({
                bucketName: userInfo?.user?.img?.bucketName || "",
                path: userInfo?.user?.img?.path || "",
              })}
              alt=""
              text={userInfo?.user?.nickName}
              onClick={() => {
                setIsOpenedLogout(true);
              }}
            />
          )}
        </div>
        <p className="party-a-title ellipsis">{partnerInfo?.projectName}</p>
        <div className="display-flex joiner-container">
          <div
            className="joiner-icons"
            onClick={() => {
              Taro.navigateTo({
                url: `/pages/project-members/index?spaceId=${spaceId}`,
              });
            }}
          >
            <StackAvatars imgs={memberList} maxLength={3} />
            <p className="joiner-number-container">
              <span className="joiner-number">共{memberList?.length}人</span>
              <span className="iconfont icon-left-line right-arrow"></span>
            </p>
          </div>
          <div
            className="invite"
            onClick={() => {
              setIsOpenedInvite(true);
            }}
          >
            邀请
          </div>
        </div>
      </div>
      <View className="flex-row tabs">
        <View className="tabs-menu" ref={menuEleRef}>
          {channelList.map((item: IChannel, index: number) => {
            return (
              <Text
                key={item.id}
                className={classNames("tabs-item", {
                  active: item.id === curChannelInfo.id,
                })}
                onClick={() => {
                  setCurChannelInfo({
                    id: item.id,
                    type: item.type,
                    name: item.name,
                  });
                }}
              >
                {item.name}
              </Text>
            );
          })}
        </View>
        <Image
          src="https://project-user-resource-1256085488.cos.ap-guangzhou.myqcloud.com/617a2ca7e4f1450011362b37/622eafe462a7d9001101bb57/16472271908592970912.png"
          className="tab-btn"
          onClick={() => {
            setIsOpened(true);
          }}
        />
      </View>
      <AllChannel
        scrollToCenter={scrollToCenter}
        isOpened={isOpened}
        setIsOpened={setIsOpened}
        channelList={channelList}
      />
      <InviteMember isOpened={isOpenedInvite} setIsOpened={setIsOpenedInvite} />
      <Logout isOpened={isOpenedLogout} setIsOpened={setIsOpenedLogout} />
    </div>
  );
};
